package com.example.myapplication.fragment;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapplication.R;
import com.example.myapplication.activity.general.WebViewActivity;
import com.example.myapplication.adapter.NewsMenuAdapter;
import com.example.myapplication.bean.BannerBean;
import com.example.myapplication.bean.NewsBean;
import com.example.myapplication.fragment.news.NDSFragment;
import com.example.myapplication.fragment.news.NGBFragment;
import com.example.myapplication.fragment.news.NJCFragment;
import com.example.myapplication.fragment.news.NLYFragment;
import com.example.myapplication.fragment.news.NSPFragment;
import com.example.myapplication.fragment.news.NSZFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author: Ng
 * @Date: 2024/4/7
 * @Versopn: 1.0.0
 */
public class NewsFragment extends BaseFragment {

    private static final String TAG = NewsFragment.class.getSimpleName();

    private ViewPager viewPager;
    private NewsMenuAdapter newsMenuAdapter;
    private TabLayout tabLayout;
    private Banner banner;
    private NewsAdapter newsAdapter;
    private ListView listView;

    private List<BannerBean.RowsDTO> banners;
    private List<NewsBean.RowsBean> news;

    @Override
    public View initView() {
        Log.i(TAG, "新闻视图实例化了..");
        View view = View.inflate(getActivity(), R.layout.fragment_news, null);
        findView(view);
        return view;
    }

    @Override
    public void initData() {
        super.initData();

        Log.i(TAG, "新闻视图的 Fragment 的数据被初始化了..");
        initMenu();
        initBanner();
        initNewsData();
    }

    private void findView(View view) {
        tabLayout = view.findViewById(R.id.fragment_news_tab_layout);
        viewPager = view.findViewById(R.id.fragment_news_view_pager);
        banner = view.findViewById(R.id.fragment_news_banner);
        listView = view.findViewById(R.id.fragment_news_list_view);
    }

    private void initMenu() {
        // 新闻分类标题导航栏
        String[] titles = {"时政", "电视", "旅游", "视频", "广播", "基层"};
        // 创建装载 Fragment 的列表
        List<Fragment> fragments;
        // 初始化列表，并把创建的 Fragment 页面添加到列表中
        fragments = new ArrayList<>();
        fragments.add(new NSZFragment());
        fragments.add(new NDSFragment());
        fragments.add(new NLYFragment());
        fragments.add(new NSPFragment());
        fragments.add(new NGBFragment());
        fragments.add(new NJCFragment());

        newsMenuAdapter = new NewsMenuAdapter(getChildFragmentManager(), fragments, titles);
        // ViewPager 与 Adapter 绑定
        viewPager.setAdapter(newsMenuAdapter);
        // TabLayout 与 ViewPager 绑定
        tabLayout.setupWithViewPager(viewPager);
    }

    private void initBanner() {
        // Banner 轮播图
        banners = new ArrayList<BannerBean.RowsDTO>();
        banners.add(new BannerBean.RowsDTO("http://pic.gooooal.com/images/102422/102422663.jpg", null));
        banners.add(new BannerBean.RowsDTO("http://pic.gooooal.com/images/102422/102422663.jpg", null));
        banners.add(new BannerBean.RowsDTO("http://pic.gooooal.com/images/102422/102422663.jpg", null));
        banner.setAdapter(new BannerImageAdapter<BannerBean.RowsDTO>(banners) {
            @Override
            public void onBindView(BannerImageHolder holder, BannerBean.RowsDTO rowsDTO, int position, int size) {
                // 加载图片
                Glide.with(getActivity())
                        .load(rowsDTO.getImgUrl())
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                        .into(holder.imageView);
            }
        }).addBannerLifecycleObserver(this)
                .setIndicator(new CircleIndicator(getActivity()))
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(Object data, int position) {
                        Toast.makeText(getActivity(), "点击了" + position, Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void initNewsData() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://172.25.77.178/news/list")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("onFailure", e.getMessage());
                // 先写固定数据显示出来
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("onFailure", "进入列表");
                        listView.setAdapter(newsAdapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                ImageView imageView = view.findViewById(R.id.news_item_image_view);
                                imageView.setDrawingCacheEnabled(Boolean.TRUE);
                                intent.putExtra("bitmap", imageView.getDrawingCache());
                                intent.putExtra("title", "测试标题");
                                intent.putExtra("time", "2024-04-09");
                                intent.putExtra("content", "测试内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容");
                                startActivity(intent);
                            }
                        });
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    Gson gson = new Gson();
                    NewsBean newsBean = gson.fromJson(result, NewsBean.class);
                    news = newsBean.getRows();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listView.setAdapter(newsAdapter);
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                    ImageView imageView = view.findViewById(R.id.news_item_image_view);
                                    imageView.setDrawingCacheEnabled(Boolean.TRUE);
                                    intent.putExtra("bitmap", imageView.getDrawingCache());
                                    intent.putExtra("title", news.get(i).getTitle());
                                    intent.putExtra("time", news.get(i).getCreateTime());
                                    intent.putExtra("content", news.get(i).getContent());
                                    startActivity(intent);
                                }
                            });
                        }
                    });
                }
            }
        });
    }

    /**
     * 新闻适配器
     */
    public class NewsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return 3;
//            return news != null ? news.size() : 0;
        }

        @Override
        public Object getItem(int i) {
            return 3;
//            return news.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
//            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                view = View.inflate(getContext(), R.layout.news_fragment_news_item,null);
                holder = new ViewHolder();
                holder.new_img = view.findViewById(R.id.news_item_image_view);
                holder.new_title = view.findViewById(R.id.news_item_title);
                holder.new_context = view.findViewById(R.id.news_item_content);
                holder.new_date = view.findViewById(R.id.news_item_date);
                holder.likeNumber = view.findViewById(R.id.news_item_like);
                holder.viewsNumber = view.findViewById(R.id.news_item_views);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
//            holder.likeNumber.setText(news.get(i).getLikeNumber());
//            holder.viewsNumber.setText(news.get(i).getViewsNumber());
//            holder.new_date.setText(news.get(i).getCreateTime());
//            holder.new_context.setText(news.get(i).getContent());
//            holder.new_title.setText(news.get(i).getTitle());
//            String url = APIConfig.BASE_URL + newsBean.getRows().get(i).getImgUrl();
//            Glide.with(getActivity()).load(url).into(holder.new_img);
            String url = "http://pic.gooooal.com/images/102422/102422663.jpg";
            Glide.with(getActivity()).load(url).into(holder.new_img);
            holder.new_title.setText("这是标题测试文本测试文本");
            holder.new_date.setText("2024-04-09");
            holder.new_context.setText("这是内容测试文本测试文本");
            holder.likeNumber.setText("22");
            holder.viewsNumber.setText("33");
            return view;
        }

        // ListView优化类
        class ViewHolder{
            ImageView new_img;
            TextView new_title;
            TextView new_context;
            TextView new_date;
            TextView viewsNumber;
            TextView likeNumber;
        }
    }
}
